package java_thinking.unit_17._17_11_13;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2019/4/22 15:01
 */

public class ReferenceTest {
    public static void main(String[] args) {
        ReferenceQueue<String> rs = new ReferenceQueue<>();
        String s = "exist";
        //软引用
        SoftReference<String> ss = new SoftReference<>(s);
        //弱引用
        WeakReference<String> ws = new WeakReference<>(s);
        //虚引用
        PhantomReference<String> ps = new PhantomReference<>(s,rs);
        System.out.println("s: "+ s);
        System.out.println("ss: "+ ss.get());
        s = null;
        System.gc();
        System.gc();
        System.gc();
        System.gc();
        System.gc();
        System.out.println("s: "+ s);
        /**
         * 软引用
         */
        //为了测试有时候会返回null
        for (int i = 0; i < 1000; i++) {
            if (ss.get() == null) {
                System.out.println("ss: " + ss.get());
            } else {
                System.gc();
            }
        }
        /**
         * 弱引用
         */
        //有时候会返回null
        System.out.println("ws: " + ws.get());
        //返回是否被垃圾回收器标记为即将回收的垃圾
        System.out.println("ws.isEnqueued: " + ws.isEnqueued());

        /**
         * 虚引用
         */
        //永远返回null
        System.out.println("ps: " + ps.get());
        //返回是否从内存中已经删除
        System.out.println("ps.isEnQueued: " + ps.isEnqueued());
    }
}

class Test {
    /**
     * 当内存足够大时可以把数组存入软引用，取数据时就可从内存里取数据，提高运行效率
     * @param args
     */
    public static void main(String[] args){
        System.out.println("开始");
        A a = new A();
        SoftReference<A> sr = new SoftReference<A>(a);
        a = null;
        if(sr!=null){
            a = sr.get();
        }
        else{
            a = new A();
            sr = new SoftReference<A>(a);
        }
        System.out.println("结束");
    }

}

class A{
    int[] a ;
    public A(){
        a = new int[100000000];
    }
}
